package com.yinhe.music.yhmusic.recent;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.annotation.Tag;
import com.hwangjr.rxbus.thread.EventThread;
import com.yinhe.music.event.RxBusEventType;
import com.yinhe.music.event.RxbusListObject;
import com.yinhe.music.yhmusic.R;
import com.yinhe.music.yhmusic.base.BaseActivity;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.constants.KeyConstants;
import com.yinhe.music.yhmusic.db.DataBaseAccessor;
import com.yinhe.music.yhmusic.db.bean.RecentMusicDBEntity;
import com.yinhe.music.yhmusic.db.bean.SongDBEntity;
import com.yinhe.music.yhmusic.dialog.more.MoreDialog;
import com.yinhe.music.yhmusic.downmusic.DownloadTask;
import com.yinhe.music.yhmusic.localmusic.view.LocalMusicDialog;
import com.yinhe.music.yhmusic.manager.ManageActivity;
import com.yinhe.music.yhmusic.model.Music;
import com.yinhe.music.yhmusic.recent.adapter.RecentListAdapter;
import com.yinhe.music.yhmusic.widget.DividerItemDecoration;
import com.yinhe.music.yhmusic.widget.WrapContentLinearLayoutManager;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hasee
 * @date 2017/2/19
 */

public class RecentPlayActivity extends BaseActivity {
    private RecyclerView mRecyclerView;
    private RecentListAdapter mAdapter;
    private LinearLayout mManager, playAll;
    private TextView mNumber;
    private List<RecentMusicDBEntity> mMusicList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recent);
        setToolbar("最近播放");
        showQuickControl(true);
        mManager = (LinearLayout) findViewById(R.id.manager);
        playAll = (LinearLayout) findViewById(R.id.play_layout);
        mNumber = (TextView) findViewById(R.id.text_num);
        mNumber.setVisibility(View.VISIBLE);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        setListener();
        setRecyclerView();

        RxBus.get().register(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    @Override
    protected void onDestroy() {
        RxBus.get().unregister(this);
        super.onDestroy();
    }

    private void setRecyclerView() {
        WrapContentLinearLayoutManager linearLayoutManager = new WrapContentLinearLayoutManager(this);
        mAdapter = new RecentListAdapter();
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL_LIST, 0, true));

        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.playlist_more) {
                    showMore(adapter, position);
                }
            }
        });

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                playMusic(adapter, position);
            }
        });
    }

    private void playMusic(BaseQuickAdapter adapter, int position) {
        if (mService != null) {
            if (!adapter.getData().isEmpty()) {
                List<Music> musicList = new ArrayList();
                for (int i = 0; i < adapter.getData().size(); i++) {
                    RecentMusicDBEntity recentMusicDBEntity = (RecentMusicDBEntity) adapter.getData().get(i);
                    musicList.add(new Music(recentMusicDBEntity));
                }

                mService.playPosition(musicList, position);
            }

        }
    }

    private void showMore(BaseQuickAdapter adapter, int position) {
        RecentMusicDBEntity recentMusicDBEntity = (RecentMusicDBEntity) adapter.getData().get(position);
        Music songInfo = new Music(recentMusicDBEntity);
        SongDBEntity songDBEntity = DataBaseAccessor.getInstance().getSongById(songInfo.songId);
        if (songDBEntity != null && songDBEntity.isSyn()) {
            LocalMusicDialog dialog = LocalMusicDialog.newInstance(songInfo, IConstants.RECENT_PLAY_MANAGER, null);
            dialog.show(getSupportFragmentManager(), KeyConstants.KEY_LOCAL_MUSIC_DIALOG);
        } else {
            MoreDialog.newInstance(songInfo, 0, IConstants.RECENT_PLAY_MANAGER).show(getSupportFragmentManager(), "MoreDialog");
        }
    }

    private void startManager() {
        Intent intent = new Intent(this, ManageActivity.class);
        intent.putExtra("manager_type", IConstants.RECENT_PLAY_MANAGER);
        startActivity(intent);
    }

    private void setPlayAll() {
        if (mService != null) {
            List<Music> musicList = new ArrayList<>();
            for (RecentMusicDBEntity recentMusicDBEntity : mMusicList) {
                musicList.add(new Music(recentMusicDBEntity));
            }
            mService.playAll(musicList);
        }
    }

    private void setListener() {
        mManager.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startManager();
            }
        });

        playAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setPlayAll();
            }
        });
    }

    private void initData() {
        setRecentSong(DataBaseAccessor.getInstance().getAllRecent());
    }

    public void setRecentSong(List<RecentMusicDBEntity> info) {
        if (info != null) {
            mMusicList = info;
            mAdapter.setNewData(info);
            mNumber.setText("(" + info.size() + ")");
            mAdapter.notifyDataSetChanged();
        }
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = {@Tag(RxBusEventType.Download.DOWNLOAD_PAUSE),
                    @Tag(RxBusEventType.Download.DOWNLOAD_START),
                    @Tag(RxBusEventType.Download.DOWNLOAD_PROCESS),
                    @Tag(RxBusEventType.Download.DOWNLOAD_CANCEL),
                    @Tag(RxBusEventType.Download.DOWNLOAD_COMPLETE),
                    @Tag(RxBusEventType.Download.DOWNLOAD_ERROR)}
    )
    public void onRxbusDownloadEvent(DownloadTask downloadTask) {
        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.Recent.DELETE_RECENT_MUSIC)
    )
    public void onRxbusDeleteRecentMusic(RxbusListObject rxbusListObject) {
        for (int i = 0; i < mMusicList.size(); i++) {
            RecentMusicDBEntity musicDBEntity = mMusicList.get(i);
            for (int j = 0; j < rxbusListObject.rxList.size(); j++) {
                int id = (Integer) rxbusListObject.rxList.get(j);
                if (musicDBEntity.getSongid() == id) {
                    mMusicList.remove(i);
                }
            }
        }
        mNumber.setText("(" + mMusicList.size() + ")");
        mAdapter.notifyDataSetChanged();
    }

    @Subscribe(
            thread = EventThread.MAIN_THREAD,
            tags = @Tag(RxBusEventType.Music.DELETE_DOWN_MUSIC)
    )
    public void onRxbusDeleteDownMusic(RxbusListObject rxbusListObject) {
        mAdapter.notifyDataSetChanged();
    }
}


